
#include "BSP_TIM.h"

TIM_IT_PTR TIM_IT_List[4] = {0};

STATUS TIM_Init(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    NVIC_InitTypeDef NVIC_InitStructure; 

    uint16_t arr, psc;

    /** 
        Tout=((arr+1)*(psc+1))/Tclk;
        Tclk = 72MHz;
    */
    psc = 36*1000-1;
    arr = 10000-1;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);  //时钟 TIM3 使能 
    
    TIM_TimeBaseStructure.TIM_Period = arr;
    TIM_TimeBaseStructure.TIM_Prescaler = psc;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);

    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    TIM_Cmd(TIM3, ENABLE);

    return ok;
}

void TIM3_IRQHandler(void)
{
    char i;
    if(TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
    {
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
        for(i=0;i<4;i++)
        {
            if(TIM_IT_List[i]!=0)
            {
                TIM_IT_List[i]();
            }
        }
    }
}

void TIM_RegIT(uint8_t seq, TIM_IT_PTR pFunc)
{
    TIM_IT_List[seq] = pFunc;
}
